package com.sebiotec.book.viewmodel;

import android.app.Application;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.AndroidViewModel;

import com.allen.library.base.BaseHttpUtil;
import com.allen.library.base.BaseObserver;
import com.allen.library.interceptor.Transformer;
import com.allen.library.observer.CommonObserver;
import com.sebiotec.basecommon.utils.constant.SjmConstant;
import com.sebiotec.basecommon.utils.entity.ACache;
import com.sebiotec.basecommon.utils.language.LocalManageUtil;
import com.sebiotec.basecommon.utils.tools.ActivityTool;
import com.sebiotec.basecommon.utils.tools.SPUtils;
import com.sebiotec.book.R;
import com.sebiotec.book.model.post.PostAddBookBean;
import com.sebiotec.book.model.post.PostLocations;
import com.sebiotec.book.model.response.AddNocationResponse;
import com.sebiotec.book.model.response.LocationsResponse;
import com.sebiotec.book.net.BookApiHelper;
import com.sebiotec.book.ui.view.LoadingDialog;
import com.google.gson.reflect.TypeToken;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function5;
import okhttp3.ResponseBody;

public class QuickAddViewModel extends AndroidViewModel {

    private  ACache aCache;
    public MyDataCallBack mDataCallBack;
    private Application application;
    //数据回调接口
    public interface MyDataCallBack<T> {
        void onDataSuccessCallBack(T t);
        void onDataFailCallBack(T t);
    }
    public QuickAddViewModel(@NonNull Application application) {
        super(application);
        this.application=application;

    }

  public void InitData(MyDataCallBack<Object> mDataCallBack){
      LoadingDialog loadingDialog = new LoadingDialog(ActivityTool.getInstance().getLastActivity());
      HashMap<String,Object> map=new HashMap<String, Object>();
      map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
      map.put("Token", SPUtils.get(SjmConstant.TOKEN,""));
      PostLocations locations=new PostLocations();
      locations.setFilter("");
      map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));
      Observable<List<LocationsResponse>> ObservablePickUpFrom = BookApiHelper.geRadomApi()
              .getLocations(map, new BaseHttpUtil<PostLocations>().convertVo2Json(locations));


      Observable<List<LocationsResponse>> Destination = BookApiHelper.geRadomApi()
              .getLocations(map, new BaseHttpUtil<PostLocations>().convertVo2Json(locations));

      Observable<List<LocationsResponse>> chargedType = BookApiHelper.geRadomApi()
              .getChargedType(map);

      Observable<List<LocationsResponse>> vehicleType = BookApiHelper.geRadomApi()
              .getVehicleType(map);

      Observable<List<AddNocationResponse>> addNotication = BookApiHelper.geRadomApi()
              .getAddNotication(map);
      //并发请求5个，等待全部结果返回后在处理
      Observable.zip(ObservablePickUpFrom, Destination, chargedType, vehicleType,addNotication,new Function5<List<LocationsResponse>, List<LocationsResponse>, List<LocationsResponse>,List<LocationsResponse>,List<AddNocationResponse>, Map<String, Object>>() {

          @RequiresApi(api = Build.VERSION_CODES.N)
          @Override
          public Map<String, Object> apply(List<LocationsResponse> s, List<LocationsResponse> s2, List<LocationsResponse> s3, List<LocationsResponse> s4, List<AddNocationResponse> addNocationResponses) throws Exception {
              Map<String, Object> objMap = new HashMap<>();
              Type type = new TypeToken<List<LocationsResponse>>() {}.getType();

//              Map<String, List<LocationsResponse>> collect = s.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));

              Map<String, List<LocationsResponse>> collect11=new LinkedHashMap<>();
              for (int i = 0; i < s.size(); i++) {
                  List<LocationsResponse> responses=new ArrayList<>();

                  responses.add(s.get(i));
                  collect11.put(s.get(i).getDescr(),responses);
              }


//              Map<String, List<LocationsResponse>> collect2 = s2.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));




              Map<String, List<LocationsResponse>> collect22=new LinkedHashMap<>();
              for (int i = 0; i < s2.size(); i++) {
                  List<LocationsResponse> responses=new ArrayList<>();

                  responses.add(s2.get(i));
                  collect22.put(s2.get(i).getDescr(),responses);
              }



//              List<LocationsResponse> list3 = GsonUtil.getGson().fromJson(s3, type);
              Map<String, List<LocationsResponse>> collect3 = s3.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));

              Map<String, List<LocationsResponse>> collect44=new LinkedHashMap<>();
              for (int i = 0; i < s4.size(); i++) {
                  List<LocationsResponse> responses=new ArrayList<>();

                  responses.add(s4.get(i));
                  collect44.put(s4.get(i).getDescr(),responses);
              }


//              List<LocationsResponse> list4 = GsonUtil.getGson().fromJson(s4, type);
//              Map<String, List<LocationsResponse>> collect4 = s4.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));

//              Map<String, List<AddNocationResponse>> collect5 = addNocationResponses.stream().collect(Collectors.groupingBy(AddNocationResponse::getName));

              Map<String, List<AddNocationResponse>> collect55=new LinkedHashMap<>();
              for (int i = 0; i < addNocationResponses.size(); i++) {
                  List<AddNocationResponse> responses=new ArrayList<>();

                  responses.add(addNocationResponses.get(i));
                  collect55.put(addNocationResponses.get(i).getName(),responses);
              }


              objMap.put("1", collect11);
              objMap.put("2", collect22);
              objMap.put("3", collect3);
              objMap.put("4", collect44);
              objMap.put("5", collect55);
              return objMap;

          }
      }).compose(Transformer.<Map<String, Object>>switchSchedulers(loadingDialog))
              .subscribe(new CommonObserver<Map<String, Object>>() {
                  @Override
                  protected String setTag() {
                      return "QuickAdd";
                  }

                  @Override
                  protected void onError(String errorMsg) {
                      mDataCallBack.onDataFailCallBack(errorMsg);
                  }

                  @Override
                  protected void onSuccess(Map<String, Object> stringObjectMap) {
                      mDataCallBack.onDataSuccessCallBack(stringObjectMap);
                  }
              });

  }


//    public  void PickUpFromData(MyDataCallBack<Object> mDataCallBack){
//        HashMap<String,Object> map=new HashMap<String, Object>();
//        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
//        map.put("Token", SPUtils.get(SjmConstant.TOKEN,""));
//        PostLocations locations=new PostLocations();
//        locations.setFilter("");
//        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));
//        BookApiHelper.geRadomApi()
//                .getLocations(map,new BaseHttpUtil<PostLocations>().convertVo2Json(locations))
//                .compose(Transformer.<String>switchSchedulers())
//                .subscribe(new CommonObserver<String>() {
//                    @Override
//                    protected void onError(String errorMsg) {
//
//                    }
//
//                    @RequiresApi(api = Build.VERSION_CODES.N)
//                    @Override
//                    protected void onSuccess(String s) {
//                        Type type = new TypeToken<List<LocationsResponse>>() {}.getType();
//                        List<LocationsResponse> list = GsonUtil.getGson().fromJson(s, type);
//                        Map<String, List<LocationsResponse>> collect = list.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));
//                        mDataCallBack.onDataSuccessCallBack(collect);
//                    }
//                });
//
//
//    }
//
//
//    public  void DestinationData(MyDataCallBack<Object> mDataCallBack){
//        HashMap<String,Object> map=new HashMap<String, Object>();
//        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
//        map.put("Token", SPUtils.get(SjmConstant.TOKEN,""));
//        PostLocations locations=new PostLocations();
//        locations.setFilter("");
//        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));
//        BookApiHelper.geRadomApi()
//                .getLocations(map,new BaseHttpUtil<PostLocations>().convertVo2Json(locations))
//                .compose(Transformer.<String>switchSchedulers())
//                .subscribe(new CommonObserver<String>() {
//                    @Override
//                    protected void onError(String errorMsg) {
//
//                    }
//
//                    @RequiresApi(api = Build.VERSION_CODES.N)
//                    @Override
//                    protected void onSuccess(String s) {
//                        Type type = new TypeToken<List<LocationsResponse>>() {}.getType();
//                        List<LocationsResponse> list = GsonUtil.getGson().fromJson(s, type);
//                        Map<String, List<LocationsResponse>> collect = list.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));
//                        mDataCallBack.onDataSuccessCallBack(collect);
//                    }
//                });
//
//    }
//    public  void ChargedTypeData(MyDataCallBack<Object> mDataCallBack){
//        HashMap<String,Object> map=new HashMap<String, Object>();
//        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
//        map.put("Token", SPUtils.get(SjmConstant.TOKEN,""));
//
//        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));
//        BookApiHelper.geRadomApi()
//                .getChargedType(map)
//                .compose(Transformer.<String>switchSchedulers())
//                .subscribe(new CommonObserver<String>() {
//                    @Override
//                    protected void onError(String errorMsg) {
//                        mDataCallBack.onDataFailCallBack(errorMsg);
//                    }
//
//                    @RequiresApi(api = Build.VERSION_CODES.N)
//                    @Override
//                    protected void onSuccess(String s) {
//                        Type type = new TypeToken<List<LocationsResponse>>() {}.getType();
//                        List<LocationsResponse> list = GsonUtil.getGson().fromJson(s, type);
//                        Map<String, List<LocationsResponse>> collect = list.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));
//                        mDataCallBack.onDataSuccessCallBack(collect);
//                    }
//                });
//
//
//    }

    public  void PaxData(MyDataCallBack<int[]> mDataCallBack){
        int[] data = new int[]{
                0, 1, 2, 3, 4,5,6,7,8,9,10
        };

        mDataCallBack.onDataSuccessCallBack(data);
    }
    public  void LugData(MyDataCallBack<int[]> mDataCallBack){
        int[] data = new int[]{
                0, 1, 2, 3, 4,5,6,7,8,9,10
        };

        mDataCallBack.onDataSuccessCallBack(data);
    }

    public  void CardData(MyDataCallBack<String[]> mDataCallBack){
        String[] data = new String[]{
                application.getString(R.string.card1),
                application.getString(R.string.card2),
                application.getString(R.string.card3),
                application.getString(R.string.card4),
                application.getString(R.string.card5)

        };


        mDataCallBack.onDataSuccessCallBack(data);
    }

//    public  void VehicleTypeData(MyDataCallBack<Object> mDataCallBack){
//        HashMap<String,Object> map=new HashMap<String, Object>();
//        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
//        map.put("Token", SPUtils.get(SjmConstant.TOKEN,""));
//
//        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));
//        BookApiHelper.geRadomApi()
//                .getVehicleType(map)
//                .compose(Transformer.<String>switchSchedulers())
//                .subscribe(new CommonObserver<String>() {
//                    @Override
//                    protected void onError(String errorMsg) {
//                        mDataCallBack.onDataFailCallBack(errorMsg);
//                    }
//
//                    @RequiresApi(api = Build.VERSION_CODES.N)
//                    @Override
//                    protected void onSuccess(String s) {
//                        Type type = new TypeToken<List<LocationsResponse>>() {}.getType();
//                        List<LocationsResponse> list = GsonUtil.getGson().fromJson(s, type);
//                        Map<String, List<LocationsResponse>> collect = list.stream().collect(Collectors.groupingBy(LocationsResponse::getDescr));
//                        mDataCallBack.onDataSuccessCallBack(collect);
//                    }
//                });
//
//    }



    public void AddNocational(MyDataCallBack<Object> mDataCallBack){
        HashMap<String,Object> map=new HashMap<String, Object>();
        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
        map.put("Token", SPUtils.get(SjmConstant.TOKEN,""));

        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));


        BookApiHelper.geRadomApi()
                .getAddNotication(map)
                .compose(Transformer.<List<AddNocationResponse>>switchSchedulers())
                .subscribe(new CommonObserver<List<AddNocationResponse>>() {
                    @Override
                    protected void onError(String errorMsg) {
                        mDataCallBack.onDataFailCallBack(errorMsg);
                    }

                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    protected void onSuccess(List<AddNocationResponse> s) {
                        Map<String, List<AddNocationResponse>> collect = s.stream().collect(Collectors.groupingBy(AddNocationResponse::getName));
                        mDataCallBack.onDataSuccessCallBack(collect);
                    }
                });
    }


    //Save
//    public PostAddBookBean
//    (String bookingId,
//    String clientId,
//    String EName, String CName,
//    int passengers, int pax, int lug, int isCheckSignboard,
//    String pickupDateTime, String fromLocId, String pickupFrom,
//    String toLocId, String destination, String other, String chargedTypeId,
//    String vechileTypeId, String signboard, String remark) {
    public  void  Save(String clientId, String EName, String CName, String passengers, int pax, int lug, int isCheckSignboard,
                       String pickupDateTime, String fromLocId, String pickupFrom, String toLocId, String destination, String other, String chargedTypeId,
                       String vechileTypeId, String signboard, String remark, String s, String AddtionalNotices, String etItinerary, int i, String trim, String trim1, MyDataCallBack<Object> mDataCallBack
    ){

        LoadingDialog loadingDialog = new LoadingDialog(ActivityTool.getInstance().getLastActivity());
        String bookingId=clientId+"-"+pickupDateTime;

        HashMap<String,Object> map=new HashMap<String, Object>();
        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
        map.put("Token", SPUtils.get(SjmConstant.TOKEN,""));

        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));

        PostAddBookBean bean=new PostAddBookBean(bookingId,clientId,EName,CName,passengers,pax,lug,isCheckSignboard,s,fromLocId,
                pickupFrom,toLocId,destination,other,chargedTypeId,vechileTypeId,signboard,remark,AddtionalNotices,etItinerary
        );
        bean.setRoundTrip(i);
        bean.setCardType(trim);
        bean.setPaymentID(trim1);
        BookApiHelper.geRadomApi()
                .ADDBookings(map,new BaseHttpUtil<PostAddBookBean>().convertVo2Json(bean))
                .compose(Transformer.<ResponseBody>switchSchedulers(loadingDialog))
                .subscribe(new BaseObserver<ResponseBody>() {
                    @Override
                    protected String setTag() {
                        return "QuickAdd";
                    }
                    @Override
                    public void doOnSubscribe(Disposable d) {

                    }

                    @Override
                    public void doOnError(String errorMsg) {
                        mDataCallBack.onDataFailCallBack(errorMsg);
                    }

                    @Override
                    public void doOnNext(ResponseBody responseBody) {
                        mDataCallBack.onDataSuccessCallBack(s);
                    }

                    @Override
                    public void doOnCompleted() {

                    }
                });




    }

}
